package com.zhehekeji.opsys.api.service.validate;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.cxf.common.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.zhehekeji.opsys.api.code.LuckyDrawResultCode;
import com.zhehekeji.opsys.api.common.util.SuperResp;
import com.zhehekeji.opsys.api.entity.TActivity;
import com.zhehekeji.opsys.api.entity.TDrawRecord;
import com.zhehekeji.opsys.api.entity.TDrawRecordDay;
import com.zhehekeji.opsys.api.entity.TUser;
import com.zhehekeji.opsys.api.service.validate.args.UserValidateArgs;

/**
 * @ClassName UserDrawValidate
 * @Description 用户抽奖验证
 * @author chenweiliu chenwei.liu@163.com
 * @date 2015-4-10   下午4:54:26
 */
@Service
public class UserDrawValidate extends ValidateService<ValidateRets<TUser>, UserValidateArgs>{

	private final static Logger logger = LoggerFactory.getLogger(UserDrawValidate.class);
	
	@Transactional(readOnly=true, propagation=Propagation.NOT_SUPPORTED)
	@Override
	public ValidateRets<TUser> validate(UserValidateArgs validateArgs) throws Exception {
		ValidateRets<TUser> validateRets = new ValidateRets<TUser>();
		SuperResp resp = validateArgs.getResp();
		String account = validateArgs.getAcount();
		int limitWinNum = validateArgs.getLimitWinNum();
		TActivity tactivity = validateArgs.getTactivity();
		//String activityCode = tactivity.getCode();
		Long activityId = tactivity.getId();
		Long cpCode = tactivity.getCpCode();
		Integer useupPoint = tactivity.getUseupPoint();
		Integer repeatWinning  =tactivity.getRepeatWinning();
		Date currentDate = validateArgs.getCurrentDate();
		if (StringUtils.isEmpty(account)){
			logger.error("账号"+account+"非法！");
			resp.setResultCode(LuckyDrawResultCode.PARAMETER_IS_NOT_LEGAL);
			resp.setResultDesc("账号非法！");
			validateRets.setSuccess(false);
			return validateRets;
		}
		
		logger.error("用户账号["+account+"]");
		TUser tmpTUser = entityDao.get(TUser.class, "o.account=?1", new Object[]{account});
		if (tmpTUser == null){
			logger.error("用户"+account+"不存在，账号非法！");
			resp.setResultCode(LuckyDrawResultCode.PARAMETER_IS_NOT_LEGAL);
			resp.setResultDesc("用户不存在，账号非法！");
			validateRets.setSuccess(false);
			return validateRets;
		}
		Integer tmpStatus = tmpTUser.getStatus();
		if (tmpStatus == 0){
			logger.error("用户"+account+"已经停用！");
			resp.setResultCode(LuckyDrawResultCode.USER_HAS_BEEN_STOPPED);
			resp.setResultDesc("用户已经停用！");
			validateRets.setSuccess(false);
			return validateRets;
		}
		
		/**
		  * 记录抽奖
		  */
		 TDrawRecord tmpTDrawRecord = new TDrawRecord();
		 tmpTDrawRecord.setCpCode(cpCode);
		 tmpTDrawRecord.setDrawTime(currentDate);
		 tmpTDrawRecord.setTactivity(tactivity);
		 tmpTDrawRecord.setAccount(account);
		 tmpTDrawRecord.setMobile(tmpTUser.getMobile());
		 entityDao.saveObj(tmpTDrawRecord);
		 
		 TDrawRecordDay tmpTDrawRecordDay = new TDrawRecordDay();
		 tmpTDrawRecordDay.setCpCode(cpCode);
		 tmpTDrawRecordDay.setDrawTime(currentDate);
		 tmpTDrawRecordDay.setTactivity(tactivity);
		 tmpTDrawRecordDay.setAccount(account);
		 tmpTDrawRecordDay.setMobile(tmpTUser.getMobile());
		 entityDao.saveObj(tmpTDrawRecordDay);
		 logger.info("是否允许重复中奖，0不允许，repeatWinning="+repeatWinning);
		 
		if (repeatWinning == 0){//不允许重复中奖
			String tmpSql = "select count(o.id) as winCount from TWinningResult o where o.tactivity.id=? and o.account=? and o.cpCode=?";
			List<Map<String, Object>> tmpListMapWinCount = entityDao.getScrollDataByHql(tmpSql, new Object[]{activityId, account, cpCode}, -1, -1);
			int tmpIntWinCount = 0;
			if (tmpListMapWinCount != null && !tmpListMapWinCount.isEmpty()){
				Map<String, Object> tmpMapWinCount = tmpListMapWinCount.get(0);
				Long tmpLongWinCount = (Long) tmpMapWinCount.get("winCount");
				tmpIntWinCount = tmpLongWinCount.intValue();
			}
			if (tmpIntWinCount > 0){
				logger.error("用户"+account+"已中奖品，谢谢参与！");
				resp.setResultCode(LuckyDrawResultCode.USER_HAS_BEEN_IN_PRIZE);
				resp.setResultDesc("用户已中奖品，谢谢参与！");
				validateRets.setSuccess(false);
				return validateRets;
			 }
		}else{//允许重发中奖
			/**
			  * 2016-01-08 添加中奖次数限制,大于0表示限制中奖次数
			  */
			 if (limitWinNum > 0){
			    String tmpSql = "select count(o.id) as winCount from TWinningResult o where o.tactivity.id=? and o.account=? and o.cpCode=?";
				List<Map<String, Object>> tmpListMapWinCount = entityDao.getScrollDataByHql(tmpSql, new Object[]{activityId, account, cpCode}, -1, -1);
				int tmpIntWinCount = 0;
				if (tmpListMapWinCount != null && !tmpListMapWinCount.isEmpty()){
					Map<String, Object> tmpMapWinCount = tmpListMapWinCount.get(0);
					Long tmpLongWinCount = (Long) tmpMapWinCount.get("winCount");
					tmpIntWinCount = tmpLongWinCount.intValue();
				}
				if (tmpIntWinCount >= limitWinNum){
					logger.info("限制中奖次数：" + limitWinNum + "，用户"+account+"已中奖次数：" + tmpIntWinCount + "，谢谢参与！");
					resp.setResultCode(LuckyDrawResultCode.THANK_YOU_IN);
					resp.setResultDesc("谢谢参与！");
					validateRets.setSuccess(false);
					return validateRets;
				 }
			 }
		}
		
		if (useupPoint != null && useupPoint > 0){
			Integer availablePoint = tmpTUser.getAvailablePoint();
			if (availablePoint == null || availablePoint.compareTo(useupPoint) < 0){
				logger.error("抽奖失败，用户"+account+"积分不足！");
				resp.setResultCode(LuckyDrawResultCode.USER_POINTS_IS_NOT_ENOUGH);
				resp.setResultDesc("抽奖失败，用户积分不足！");
				validateRets.setSuccess(false);
				return validateRets;
			}
		}
		validateRets.setEntity(tmpTUser);
		return validateRets;
	}
}
